﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Grundy.Common;

namespace Grundy.Message
{
    [DataContract]
    [KnownType(typeof(BiosIdentifier))]
    [KnownType(typeof(CheckoutIdentifier))]
    [KnownType(typeof(HostnameIdentifier))]
    [KnownType(typeof(MacAddressIdentifier))]
    [KnownType(typeof(ProcessIdentifier))]
    [KnownType(typeof(ProcessorIdentifier))]
    [KnownType(typeof(TerminalServicesIdentifier))]
    [KnownType(typeof(UserNameIdentifier))]
    [KnownType(typeof(UserSidIdentifier))]
    public abstract class Identifier
    {
        public bool Equals(Identifier other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Equals(other.Name, Name) && Equals(other.Value, Value);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (!typeof(Identifier).IsAssignableFrom(obj.GetType())) return false;
            return Equals((Identifier) obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return ((Name != null ? Name.GetHashCode() : 0)*397) ^ (Value != null ? Value.GetHashCode() : 0);
            }
        }

        public static bool operator ==(Identifier left, Identifier right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(Identifier left, Identifier right)
        {
            return !Equals(left, right);
        }

        public Guid Id { get; set; }

        [Required]
        [DataMember]
        public string Name { get; set; }

        [Required]
        [DataMember]
        public string Value { get; set; }

        private bool _ignore;

        [DataMember]
        public bool Ignore
        {
            get { return _ignore; }
            set { _ignore = value; }
        }

        public Identifier Copy()
        {
            var newIdentifier = (Identifier)Activator.CreateInstance(this.GetType());
            newIdentifier.Id = Guid.NewGuid();
            newIdentifier.Ignore = this.Ignore;
            newIdentifier.Value = this.Value;
            return newIdentifier;
        }

        public override string ToString()
        {
            return "{{{0} : {1}, Mandatory: {2}}}".FormatWith(Name, Value, !Ignore);
        }
    }
}